<?php
namespace aes;
/**
 * 常用对称加密算法类
 * 支持密钥：64/128/256 bit（字节长度8/16/32）
 * 支持算法：DES/AES（根据密钥长度自动匹配使用：DES:64bit AES:128/256bit）
 * 支持模式：CBC/ECB/OFB/CFB
 * 密文编码：base64字符串/十六进制字符串/二进制字符串流
 * 填充方式: PKCS5Padding（DES）
 */
class CryptAES
{

    private $hex_iv = 'SHOPvhREw5IVXAnT'; //初始化向量16位

    private $key = 'NjeRkITGhDvaFsRT8En2HgUaPS7fZ6Q4'; //默认密钥32位

    public function __construct($key) {
        $this->key = $key;
        $this->key = hash('sha256', $this->key, true);
    }

    /**
     * @desc AES加密
     * @param string $string 待加密明文字符串
     * @return false|string
     */
    public function encrypt($string)
    {
        $data = openssl_encrypt(
            $string,
            'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hex_iv);
        $data = base64_encode($data);
        return $data;
    }

    /**
     * @desc AES解密
     * @param string $cryptString 已加密文
     * @return false|string
     */
    public function decrypt($cryptString)
    {
        return openssl_decrypt(
            base64_decode($cryptString),
            'AES-256-CBC', $this->key,
            OPENSSL_RAW_DATA,
            $this->hex_iv);
    }

    private function addPadding($string, $blockSize = 16) {
        $len = strlen($string);
        $pad = $blockSize - ($len % $blockSize);
        $string .= str_repeat(chr($pad), $pad);
        return $string;
    }

    private function strPadding($string) {
        $slast = ord(substr($string, -1));
        $slastc = chr($slast);
        $pcheck = substr($string, -$slast);
        if (preg_match("/$slastc{" . $slast . "}/", $string)) {
            $string = substr($string, 0, strlen($string) - $slast);
            return $string;
        } else {
            return false;
        }
    }

    public function hexToStr($hex)
    {
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2)
        {
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }

}